@echo off
setlocal enabledelayedexpansion


@REM 获取固件信息,获取指定行（3行）的数据
if exist firmware_info.ini del firmware_info.ini
(..\exeTools\srecord-1.65.0-win64\bin\srec_info.exe ..\MDKProject\build\GD32F470ZIT6.hex -intel)>>firmware_info.ini
set "iniFilePath=.\firmware_info.ini"

@REM 打印固件信息
echo ****************************************************************************************************************************
set count=0
for /f "usebackq delims=" %%a in ("%iniFilePath%") do (
    set /a count+=1
    echo %%a""
)

@REM 获取固件开始和结束地址，并提取地址内容
set count=0
for /f "usebackq delims=" %%a in ("%iniFilePath%") do (
    set /a count+=1
    if !count! equ 3 (
        set firmware_addr=%%a
        goto :found
    )
)
:found
del firmware_info.ini

@REM 提取字符串中的数值部分（开始地址和结束地址）
set count=0
for %%i in (%firmware_addr%) do (
    @REM echo Extracted number %%i
    set /a count+=1
    if !count! == 2 (
        set "startAddr=%%i"
    )
    if !count! == 4 (
        set "endAddr=%%i"
    )
)
@REM 打印开始地址和结束地址
echo APP_startAddr  = 0x!startAddr! 
echo APP_endAddr    = 0x!endAddr!
echo ****************************************************************************************************************************

@REM 将bin文件求crc32校验后将校验值添加到固件的末尾位置
..\exeTools\srecord-1.65.0-win64\bin\srec_cat.exe  ..\MDKProject\build\GD32F470ZIT6.hex -intel -crc32-l-e -maximum-address ..\MDKProject\build\GD32F470ZIT6.hex -intel -o ..\MDKProject\build\GD32F470ZIT6.hex -intel

@REM 将固件的开始地址和结束地址存储到Flash特定地方
@REM ..\exeTools\srecord-1.65.0-win64\bin\srec_cat.exe -generate 0x0800A090 0x0800A0A0 -repeat-string !startAddr!!endAddr! ..\MDKProject\build\GD32F470ZIT6.hex -intel -exclude 0x0800A090 0x0800A09F -o ..\MDKProject\build\GD32F470ZIT6.hex -intel

@REM 将hex文件转化成bin文件
JFlash.exe -open ..\MDKProject\build\GD32F470ZIT6.hex -saveas ..\MDKProject\build\GD32F470ZIT6.bin -exit

@REM 删除编译后无用的文件
set "ext=..\MDKProject\build\*.o"
 
:: 遍历当前目录及其子目录
@REM for /r %%i in (%ext%) do (
@REM     del "%%i"
@REM )
@REM set "ext=..\MDKProject\build\*.d"
@REM for /r %%i in (%ext%) do (
@REM     del "%%i"
@REM )
@REM set "ext=..\MDKProject\build\*.__i"
@REM for /r %%i in (%ext%) do (
@REM     del "%%i"
@REM )
@REM set "ext=..\MDKProject\build\*._ac"
@REM for /r %%i in (%ext%) do (
@REM     del "%%i"
@REM )
@REM set "ext=..\MDKProject\build\*.axf"
@REM for /r %%i in (%ext%) do (
@REM     del "%%i"
@REM )
@REM set "ext=..\MDKProject\build\*.dep"
@REM for /r %%i in (%ext%) do (
@REM     del "%%i"
@REM )
@REM set "ext=..\MDKProject\build\*.lnp"
@REM for /r %%i in (%ext%) do (
@REM     del "%%i"
@REM )
@REM set "ext=..\MDKProject\build\*.sct"
@REM for /r %%i in (%ext%) do (
@REM     del "%%i"
@REM )



@REM pause
